package core

import (
	"fmt"
	"time"
)

type Bar struct {
	percent     int64   //百分比
	cur         int64   //当前进度量（已经完成的量）
	total       int64   //总进度
	rateCode    string  //进度条
	graph       string  //显示符号
	displayRate float64 //进度条每格代表比例
	windowWidth int64   // 窗口宽度
}

// getPercent 获取百分比
func (bar *Bar) getPercent() int64 {
	if bar.total <= 0 {
		return 0
	}
	return bar.cur * 100 / bar.total
}

// NewOptionWithGraph 个性化初始化进度条
func (bar *Bar) newOptionWithGraph(start, total, windowWidth int64, graph string) {
	bar.graph = graph
	bar.windowWidth = windowWidth
	bar.cur += start
	bar.total = total
	if bar.graph == "" {
		bar.graph = "="
	}

	// 假设进度条整体使用命令行窗口的一半宽度，合理的将每次进度显示在合理的字符宽度上面。
	if 100/(bar.windowWidth/2) >= 1 {
		bar.displayRate = 100/(float64(bar.windowWidth)/2) + 1
	} else {
		bar.displayRate = 1
	}
	bar.percent = bar.getPercent()
	bar.rateCode = ""
	for i := bar.percent; i >= 0; i -= 2 {
		bar.rateCode += bar.graph //初始化进度条位置
	}
}

// Play 进度条展示
func (bar *Bar) Play(cur int64, isBar bool, unitStr string, start time.Time) {
	if !isBar {
		return
	}
	// 如果窗口过小，不显示进度条以后的东西0为全显示，尺寸足够，1为缩减进度条以后的东西。-1为省略进度条只剩下百分百进度。
	minBar := 0
	if bar.windowWidth/2 < 32 && bar.windowWidth/2 >= 10 {
		minBar = 1
	}
	if bar.windowWidth/2 < 10 {
		minBar = -1
	}
	bar.cur += cur
	bar.percent = bar.getPercent()
	bar.rateCode = ""
	// fmt.Println(w, bar.percent, bar.rateCode, bar.displayRate, 100/(w/2))
	var j, k float64
	for j = 0; j < float64(bar.percent)/bar.displayRate; j++ {
		bar.rateCode += bar.graph
	}
	for k = 0; k < float64(100-bar.percent)/bar.displayRate; k++ {
		bar.rateCode += "-"
	}

	// 显示单位
	unit := MB
	switch unitStr {
	case "B":
		unit = B
	case "KB":
		unit = KB
	case "MB":
		unit = MB
	case "GB":
		unit = GB
	case "TB":
		unit = TB
	default:
	}
	switch minBar {
	case -1:
		fmt.Printf("\r%d%% ", bar.percent)
	case 0:
		fmt.Printf("\r%s%3d%%  %8.2f%s/%.2f%s %.2fs", bar.rateCode, bar.percent, float64(bar.cur)/float64(unit), unitStr, float64(bar.total)/float64(unit), unitStr, time.Since(start).Seconds())
	case 1:
		fmt.Printf("\r%s%3d%% ", bar.rateCode, bar.percent)
	default:
	}

}

// // Finish 结束
// func (bar *Bar) Finish() {
// 	fmt.Println()
// }
